// 云函数入口文件
const cloud = require('wx-server-sdk')
const cheerio=require('cheerio')// 操作html结构
const charset=require('superagent-charset')// 解决乱码
const superagent=require('superagent')// 发接口请求
charset(superagent)

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  let serverUrl='https://m.biqiugege8.com/'  // 接口地址
  const result=await (superagent.get(serverUrl)).charset('gb2312')
  const data=result.text||"";
  const $=cheerio.load(data);

  // 热门推荐
  let hotList=$('.hot').find('.image')
  let hotData=[]
  for(let i=0;i<hotList.length;i++){
    let obj={}
    obj['url']=$(hotList[i]).find('a').attr('href')
    obj['imgUrl']=$(hotList[i]).find('img').attr('src')
    obj['name']=$(hotList[i]).find('img').attr('alt')
    obj['author']=$(hotList[i]).next().find('dt').find('span').text()
    obj['detail']=$(hotList[i]).next().find('dd').text()
    hotData.push(obj)
  }

  // 分类
  let classifyData=[]
  let classifyList=$('.block')
  for(let parent of classifyList){
    let childDom=$(parent).find('.lis').find('li')
    let obj={}
    let childData=[]
    for(let child of childDom){
      let childObj={}
      childObj['name']=$(child).find('.s2').find('a').text()
      childObj['url']=$(child).find('.s2').find('a').attr('href')
      childObj['author']=$(child).find('.s3').text()
      childData.push(childObj)
    }

    obj['title']=$(parent).find('h2').text()
    obj['list']=childData
    classifyData.push(obj)
  }
  return {
    hotData,
    classifyData
  }
}